package com.edgar.baselibrary.network;

import android.util.Log;

import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;

/**
 * Created by edgar on 2016/1/22.
 */
public final class MessageCode {
    /**
     * 当请求服务器成功,但是返回的数据不正常.
     * <p>
     * 1.解析失败;
     * </p>
     * <p>
     * 2.服务器返回errorMsg
     * </p>
     */
    public static final int FAIL = 0;
    /**
     * 请求服务器成功,并且数据解析正常.
     */
    public static final int SUCCEED = 1;
    /**
     * 连接超时
     */
    public static final int TIME_OUT = 1000;
    /**
     * 网络异常
     */
    public static final int NETWORK_ERROR = 1001;
    /**
     * 服务器异常
     */
    public static final int SERVER_ERROR = 1002;
    /**
     * 未知错误
     */
    public static final int UNKNOWN_ERROR = 1003;

    private static final String TAG = MessageCode.class.getSimpleName();
    public static ResponseException getResponseErrorByVolleyError(VolleyError e) {
        String errorMsg = "";
        int errorCode = UNKNOWN_ERROR;
        NetworkResponse networkResponse = e.networkResponse;
        if (networkResponse != null && networkResponse.data != null) {
            errorMsg = new String(networkResponse.data);
        } else {
            errorMsg = e.getMessage();
        }
        Log.e(TAG, "errorCode: " + errorCode + "errorMsg:" + errorMsg);
        if (e instanceof TimeoutError) {
            errorCode = TIME_OUT;
            errorMsg = "连接超时";
        } else if (e instanceof NetworkError) {
            errorCode = NETWORK_ERROR;
            errorMsg = "网络异常";
        } else if (e instanceof ServerError) {
            errorCode = SERVER_ERROR;
            errorMsg = "服务器异常";
        } else {
            errorCode = UNKNOWN_ERROR;
            errorMsg = "未知错误";
        }
        return new ResponseException(errorCode, errorMsg);
    }
}